const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const {
  createUser,
  getUserInfo,
  updateById,
} = require("../service/user.service");
const {
  userCreateSuccess,
  userLoginSuccess,
  userChangePasswordSuccess,
} = require("../constant/successType");
const {
  userFormDataError,
  authInvalidError,
} = require("../constant/errorType");
const successType = require("../constant/successType");

class UserController {
  // 注册
  async register(ctx) {
    const { userName, password, nickName } = ctx.request.body;

    await createUser(
      {
        user_name: userName,
        password,
        nick_name: nickName || userName,
      },
      ctx
    );

    ctx.body = userCreateSuccess;
  }

  // 登录
  async login(ctx) {
    const { userName } = ctx.request.body;
    const res = await getUserInfo({ user_name: userName }, ctx);
    const { password, ...userInfo } = res;
    const { id, user_name, nick_name, is_admin } = userInfo;
    ctx.body = {
      ...userLoginSuccess,
      result: {
        token: jwt.sign(userInfo, process.env.JWT_SECRET, { expiresIn: "3h" }),
        userId: id,
        userName: user_name,
        nickName: nick_name,
        isAdmin: is_admin,
      },
    };
  }

  // 修改密码
  async changePassword(ctx) {
    const { id } = ctx.state.userInfo;
    const { oldPassword, password } = ctx.request.body;
    if (!password) return ctx.app.emit("error", userFormDataError, ctx);
    const res = await getUserInfo({ id }, ctx);
    if (!res || !bcrypt.compareSync(oldPassword, res.password))
      return ctx.app.emit("error", authInvalidError, ctx);
    await updateById({ id, password }, ctx);
    ctx.body = userChangePasswordSuccess;
  }

  // 修改昵称
  async changeNickName(ctx) {
    const { id } = ctx.state.userInfo;
    const { nickName } = ctx.request.body;
    await updateById({ id, nickName }, ctx);
    ctx.body = successType.userChangeNickNameSuccess;
  }
}

module.exports = new UserController();
